using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using Opc.Ua;
using Opc.Ua.Client;
using Opc.Ua.Sample.Service;
using OpcuaClient.Model;
using OpcuaClient.Service;

namespace OpcuaClient.View
{
    public partial class Form_ConstructionConfig : Form
    {
        private OpcConnectService ServerService { get; set; }
        public Construction Construction { get; set; }
        public List<NodeId> Nodes { get; set; }
        public List<ConstructionKeyValue> KeyValues { get; set; }
        private List<Collection> Collections { get; set; }
        public bool Status { get; set; }
        private NodeId Node { get; set; }
        private ListViewService ListViewService { get; set; }

        public Form_ConstructionConfig(Construction construction = null)
        {
            InitializeComponent();
            Nodes = new List<NodeId>();
            KeyValues = new List<ConstructionKeyValue>();
            Collections = new List<Collection>();
            Construction = construction;

            ListViewService = new ListViewService(lvKeyValue);
        }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="construction"></param>
        /// <param name="collections"></param>
        public void InitNodeSource(OpcConnectService serverService, List<Collection> collections)
        {
            if (Construction == null)
            {
                CreateConstruction();
            }

            ServerService = serverService;
            List<NodeId> leftNodes = new List<NodeId>();
            List<NodeId> rightNodes = new List<NodeId>();
            //结构体参数
            Collections = collections;
            lvNodeList.BeginUpdate();
            foreach (var item in Collections)
            {
                if (item.Node == null)
                {
                    item.Node = NodeId.Parse(item.Address);
                }
                leftNodes.Add(item.Node);

                ListViewItem viewItem = new ListViewItem();
                viewItem.ImageIndex = lvNodeList.Items.Count;
                viewItem.Text = item.Name;
                viewItem.SubItems.Add(item.Address);
                viewItem.Tag = item;
                lvNodeList.Items.Add(viewItem);
            }
            lvNodeList.EndUpdate();
            lvNodeList.Refresh();

            //KeyValue
            KeyValues = Construction.KeyValues;
            foreach (var item in Construction.KeyValues)
            {
                rightNodes.Add(item.Node);
            }

            ListViewService.AddItems(Construction.KeyValues);
        }

        private void lvNodeList_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
        }

        private void lvNodeList_DoubleClick(object sender, EventArgs e)
        {
            var items = lvNodeList.SelectedItems;
            if (items.Count == 0) return;
            Collection collection = (Collection)items[0].Tag;
            if (Construction == null)
            {
                CreateConstruction();
            }
            InitKeyValue(collection);
            Nodes.Add(collection.Node);
        }

        private void InitKeyValue(Collection collection)
        {
            if (collection == null) return;
            //string[] values = collection.Node.Identifier.ToString().Split('/');
            //if (values.Length < 2)
            //{
            //    values = collection.Node.Identifier.ToString().Split('.');
            //}
            tbKey.Text = collection.Key;
            tbName.Text = collection.Name;
            tbCode.Text = collection.Key;
            cbIsKeyword.Checked = false;
            tbValue.Text = collection != null ? collection.Value.ToString() : "";
            tbFilter.Text = "";
            Node = collection.Node;
        }

        private void InitKeyValue(ConstructionKeyValue keyValue)
        {
            tbKey.Text = keyValue.Key;
            tbName.Text = keyValue.Name;
            tbCode.Text = keyValue.Code;
            tbValue.Text = keyValue.Value.ToString();
            tbPrecondition.Text = keyValue.Precondition;
            tbPreFrequency.Text = keyValue.PreFrequency.ToString();
            cbIsKeyword.Checked = keyValue.IsKeyWord;
            tbFilter.Text = keyValue.Filter;
            Node = NodeId.Parse(keyValue.Address);
        }

        /// <summary>
        /// 配置结构体参数
        /// </summary>
        /// <returns></returns>
        private Construction CreateConstruction()
        {
            Form_Construction construction = new Form_Construction();
            construction.Config(Construction);
            construction.ShowDialog(this);
            if (construction.Status)
            {
                Construction = construction.Construction;
            }
            else
            {
                Construction = new Construction();
            }
            return Construction;
        }

        private void btCancel_Click(object sender, EventArgs e)
        {
            Node = null;

            tbKey.Text = "";
            tbName.Text = "";
            tbCode.Text = "";
            tbValue.Text = "";
            cbIsKeyword.Checked = false;
            tbPrecondition.Text = "";
            tbPreFrequency.Text = "";
            tbFilter.Text = "";
        }

        private void btSave_Click(object sender, EventArgs e)
        {
            ConstructionKeyValue keyValue = KeyValues.FirstOrDefault(m => m.Node == Node);
            if (keyValue == null)
            {
                keyValue = new ConstructionKeyValue() {
                    Key = tbKey.Text,
                    Name = tbName.Text,
                    Code = tbCode.Text,
                    IsKeyWord = cbIsKeyword.Checked,
                    Value = tbValue.Text,
                    Precondition = tbPrecondition.Text,
                    PreFrequency = string.IsNullOrWhiteSpace(tbPreFrequency.Text) ? 0 : int.Parse(tbPreFrequency.Text),
                    Filter = tbFilter.Text,
                    Node = Node
                };
                KeyValues.Add(keyValue);
            }
            else
            {
                int idx = KeyValues.IndexOf(keyValue);

                keyValue.Key = tbKey.Text;
                keyValue.Name = tbName.Text;
                keyValue.Code = tbCode.Text;
                keyValue.IsKeyWord = cbIsKeyword.Checked;
                keyValue.Value = tbValue.Text;
                keyValue.Precondition = tbPrecondition.Text;
                keyValue.PreFrequency = string.IsNullOrWhiteSpace(tbPreFrequency.Text) ? 0 : int.Parse(tbPreFrequency.Text);
                keyValue.Filter = tbFilter.Text;
                keyValue.Node = Node;

                KeyValues[idx] = keyValue;
            }
            //将KEYVALUE添加到LISTVIEW
            ListViewService.AddItem(keyValue);
        }

        private void Form_ConstructionConfig_Load(object sender, EventArgs e)
        {

        }

        private void btMidifyConstruction_Click(object sender, EventArgs e)
        {
            CreateConstruction();
        }

        private void rbIsKeyword_Click(object sender, EventArgs e)
        {
            RadioButton radioButton = (RadioButton)sender;
            if (!radioButton.Checked)
            {
                radioButton.Checked = false;
            }
        }
        /// <summary>
        /// 删除当前选定项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 删除当前选项ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var items = lvKeyValue.SelectedItems;
            if (items.Count == 0) return;
            var result = MessageBox.Show(this, "您确定要删除这些选项吗？", "太危险了！", MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2);
            if (result == DialogResult.No) return;
            foreach (ListViewItem item in items)
            {
                lvKeyValue.Items.Remove(item);
                var keyValue = (ConstructionKeyValue)item.Tag;
                KeyValues.Remove(keyValue);

                Nodes.Remove(keyValue.Node);
            }
        }

        private void Form_ConstructionConfig_FormClosing(object sender, FormClosingEventArgs e)
        {
            Status = false;
            var retsult=MessageBox.Show(this, "是否保存退出A？", "提示！", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1);
            if(DialogResult.Yes == retsult)
            {
                Status = true;
            }
            if (Construction == null) return;
            Construction.KeyValues = KeyValues;
        }

        private void lvKeyValue_DoubleClick(object sender, EventArgs e)
        {
            var items = lvKeyValue.SelectedItems;
            if (items.Count == 0) return;
            InitKeyValue((ConstructionKeyValue)items[0].Tag);
        }
    }
}
